package org.ishequ.miduo.weibo;

import org.ishequ.miduo.R;
import java.util.ArrayList;
import java.util.List;
import org.ishequ.miduo.MiDuoActivity.ConfigHelper;
import org.ishequ.weibo.adapater.CommentAdapter;
import org.ishequ.weibo.domain.UserInfo;
import org.ishequ.weibo.utils.InfoHelper;
import org.ishequ.weibo.utils.http.AsyncImageLoader;
import org.ishequ.weibo.utils.http.AsyncImageLoader.ImageCallback;
import org.ishequ.widget.HighLightTextView;
import weibo4android.Comment;
import weibo4android.Count;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.TextView;

public class WeiboViewActivity extends BaseActivity {

	private UserInfo user;
	private long weiboID;
	
	private Status status;
	private List<Comment> comments = new ArrayList<Comment>();
	List<Count> counts ;
	
	private TextView utv;
	private ImageView user_iv;
	private ImageView pic;
	private TextView no_comment;
	private HighLightTextView ttv;
	private Button btn_retweet;
	private Button btn_comment;
	private RelativeLayout ff;
	private LinearLayout ll;
	private SlidingDrawer slidingDrawer;
	private ListView listView;
	private CommentAdapter adapter = new CommentAdapter(WeiboViewActivity.this, comments);
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case InfoHelper.LOADING_DATA_FAILED:
					Toast.makeText(WeiboViewActivity.this, "获取信息失败",
							Toast.LENGTH_LONG).show();
					WeiboViewActivity.this.finish();
					break;
				case InfoHelper.LOADING_DATA_COMPLETED:
					adapter.notifyDataSetChanged();
//					Toast.makeText(WeiboViewActivity.this, "刷新完成", Toast.LENGTH_LONG)
//							.show();
					ff.setVisibility(View.VISIBLE);
					ll.setVisibility(View.GONE);
					if (comments.size() == 0) {
						no_comment.setVisibility(View.VISIBLE);
						listView.setVisibility(View.GONE);
					} else {
						no_comment.setVisibility(View.GONE);
						listView.setVisibility(View.VISIBLE);
					}
					view();
					break;
			}
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.weibo_view, null);
		root.addView(layout);
		
		// 设置标题栏文字
		titlebarText.setText("阅读微博");
		
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
    	
    	user = ConfigHelper.nowUser;
    	
    	Bundle bundle = getIntent().getExtras();
		if (bundle == null || !bundle.containsKey("cid")) {
			Toast.makeText(this, "获取微博信息失败", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		weiboID = bundle.getLong("cid");
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Weibo weibo = new Weibo();
					weibo.setToken(user.getToken(), user.getTokenSecret());
					status = weibo.showStatus(weiboID);
					comments = weibo.getComments(weiboID + "");
					adapter.setComments(comments);
					counts = weibo.getCounts(weiboID + "");
					handler.sendEmptyMessage(InfoHelper.LOADING_DATA_COMPLETED);
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(InfoHelper.LOADING_DATA_FAILED);
					return;
				}
			}
		}).start();
		
		utv = (TextView) layout.findViewById(R.id.user_name);
		ttv = (HighLightTextView) layout.findViewById(R.id.text);
		user_iv = (ImageView) layout.findViewById(R.id.user_icon);
		pic = (ImageView) layout.findViewById(R.id.pic);
		
		btn_comment = (Button) layout.findViewById(R.id.weibo_btn_comment);
		btn_retweet = (Button) layout.findViewById(R.id.weibo_btn_retweet);
		slidingDrawer = (SlidingDrawer) layout.findViewById(R.id.slidingdrawer);
		no_comment = (TextView) layout.findViewById(R.id.weibo_no_comment);
		
		ff = (RelativeLayout) layout.findViewById(R.id.weibo_ff);
		ll = (LinearLayout) layout.findViewById(R.id.weibo_waitingView);

		listView = (ListView) layout.findViewById(R.id.slide_listView);
		listView.setCacheColorHint(0);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				new WeiboCommentMentionDialog(WeiboViewActivity.this, true, weiboID,
						comments.get(position).getId() + "");
			}
		});
		
		btn_comment.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new WeiboCommentMentionDialog(WeiboViewActivity.this, true, weiboID, null);
			}
		});

		btn_retweet.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new WeiboCommentMentionDialog(WeiboViewActivity.this, false, weiboID,
						null);
			}
		});

		slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			@Override
			public void onDrawerClosed() {
				if (comments.size() == 0) {
					no_comment.setVisibility(View.VISIBLE);
					listView.setVisibility(View.GONE);
				} else {
					no_comment.setVisibility(View.GONE);
					listView.setVisibility(View.VISIBLE);
				}
				adapter.notifyDataSetChanged();
			}
		});
		
	}

	private void view() {
		try {
        	if(status != null) {
            	User weibo_user = status.getUser();
            	String userName = weibo_user.getScreenName();
				String userIcon = weibo_user.getProfileImageURL().toString();
				Log.i("userIcon", userIcon);
//				Date nowDate = Calendar.getInstance().getTime();
//				String time = new DateUtilsDef().twoDateDistance(status.getCreatedAt(),nowDate)+ "前";
				String text = status.getText();
				
				if (status.getRetweeted_status() != null) {
					text = text + "\n\n转自: @"
							+ status.getRetweeted_status().getUser().getScreenName()
							+ " : " + status.getRetweeted_status().getText();
					if (!TextUtils.isEmpty(status.getRetweeted_status()
							.getThumbnail_pic())) {
						pic.setVisibility(View.VISIBLE);
					}
				} else if (!TextUtils.isEmpty(status.getThumbnail_pic())) {
					pic.setVisibility(View.VISIBLE);
				}
				
				utv.setText(userName);
				ttv.setText(text);

				//异步加载头像
				AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
				Drawable cachedImage = asyncImageLoader.loadDrawable(
						userIcon, user_iv, new ImageCallback() {
							public void imageLoaded(Drawable imageDrawable,
									ImageView imageView, String imageUrl) {
								imageView.setImageDrawable(imageDrawable);
							}
						});
				if (cachedImage == null) {
					user_iv.setImageResource(R.drawable.weibo_avatar);
				} else {
					user_iv.setImageDrawable(cachedImage);
				}
				
				if (status.getBmiddle_pic() != null && !"".equals(status.getBmiddle_pic())) {
					String picurl = status.getBmiddle_pic();
					String picurl2 = status.getOriginal_pic();
					pic.setTag(picurl2);
					pic.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							Object obj = v.getTag();
							Intent intent = new Intent(WeiboViewActivity.this,
									WeiboImageActivity.class);
							Bundle b = new Bundle();
							b.putString("url", obj.toString());
							intent.putExtras(b);
							startActivity(intent);
						}
					});
					//异步加载图片
					Drawable cachedImage2 = asyncImageLoader.loadDrawable(
							picurl, pic, new ImageCallback() {
								public void imageLoaded(
										Drawable imageDrawable,
										ImageView imageView, String imageUrl) {
									showImg(imageView, imageDrawable);
								}
							});
					if (cachedImage2 == null) {
						pic.setImageResource(R.drawable.weibo_ic_launcher);
					} else {
						showImg(pic, cachedImage2);
					}
				}
        	}
        	
        	if(counts != null && counts.size()>0){
        		Count count = counts.get(0);
        		String comments = String.valueOf(count.getComments());
        		String rt = String.valueOf(count.getRt());
        		Button btn_gz = (Button) findViewById(R.id.weibo_btn_retweet);
        		btn_gz.setText("        转发(" + rt + ")");
        		Button btn_pl = (Button) findViewById(R.id.weibo_btn_comment);
        		btn_pl.setText("        评论(" + comments + ")");
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void showImg(ImageView view, Drawable img) {
		int w = img.getIntrinsicWidth();
		int h = img.getIntrinsicHeight();
		Log.i("w", w + "/" + h);
		if (w > 300) {
			int hh = 300 * h / w;
			Log.e("hh", hh + "");
			LayoutParams para = (LayoutParams) view.getLayoutParams();
			para.width = 300;
			para.height = hh;
			view.setLayoutParams(para);
		}
		view.setImageDrawable(img);
	}
}
